<template>
  <v-line
    v-for="line in xAxisList"
    :key="line.x"
    :points="[line.x, line.y, line.x, line.y + line.height]"
    :stroke="line.stroke"
    :strokeWidth="1"
  />
  <v-line
    v-for="line in yAxisList"
    :key="line.y"
    :points="[line.x, line.y, line.x + line.width, line.y]"
    :stroke="line.stroke"
    :strokeWidth="1"
  />
  <v-text
    v-for="text in xAxisTextList"
    :key="text.x"
    :x="text.x"
    :y="text.y"
    align="center"
    :text="text.text"
  />
  <v-text
    v-for="text in yAxisTextList"
    :key="text.y"
    :x="text.x"
    :y="text.y"
    align="center"
    :text="text.text"
  />
</template>
<script>
export default {
  name: 'coordinateAxis',
  props: {
    width: {
      type: Number,
      default: 0,
    },
    height: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      // 网格粒度
      grid: 100,
      xAxisList: [],
      xAxisTextList: [],
      yAxisList: [],
      yAxisTextList: [],
    }
  },
  watch: {
    width() {
      this.renderWidth()
      this.renderCenterLine()
    },
    height() {
      this.renderHeight()
      this.renderCenterLine()
    },
  },
  created() {
    this.renderWidth()
    this.renderHeight()
    this.renderCenterLine()
  },
  methods: {
    renderWidth() {
      this.xAxisList = []
      this.xAxisTextList = []
      for (let i = 0; i < this.width; i += this.grid) {
        this.xAxisList.push({
          x: i,
          y: 0,
          height: this.height,
          stroke: '#ccc',
        })
        this.xAxisTextList.push({
          x: i,
          y: this.height / 2 + 5,
          text: i || '',
        })
        this.xAxisTextList.push({
          x: i,
          y: 0,
          text: i || '',
        })
      }
    },
    renderHeight() {
      this.yAxisList = []
      for (let i = 0; i < this.height; i += this.grid) {
        this.yAxisList.push({
          x: 0,
          y: i,
          width: this.width,
          stroke: '#ccc',
        })
        this.yAxisTextList.push({
          x: this.width / 2 + 5,
          y: i,
          text: i || '',
        })
        this.yAxisTextList.push({
          x: 0,
          y: i,
          text: i || '',
        })
      }
    },
    // 渲染中轴线
    renderCenterLine() {
      this.xAxisList.push({
        x: this.width / 2,
        y: 0,
        height: this.height,
        stroke: '#000',
      })
      this.yAxisList.push({
        x: 0,
        y: this.height / 2,
        width: this.width,
        stroke: '#000',
      })
    },
  },
}
</script>
